package com.hancheng.commoncloud.framework.util;

import org.apache.commons.codec.digest.DigestUtils;

import java.util.LinkedHashMap;
import java.util.Map;
import java.util.stream.Collectors;

public class SecretUtil {
    /**
     * 签名key
     */
    private static final String ACCESS_SECRET = "secret";

    /**
     * 获取签名,Map.key 升序排序后由MD5加密,加密串格式: param1=1232&param2=1232&param3=1232&secret=sdhashdiib123ibuYgqsaiJgsuVsai
     * @param params 加密参数
     * @param accessSecret
     * @return
     */
    public static String sign(Map<String, Object> params, String accessSecret) {
        params = sortByKeyAsc(params);
        StringBuilder temp = new StringBuilder();
        params.forEach((key, value) -> {
            if (temp.length() > 0) {
                temp.append("&");
            }
            temp.append(key).append("=");
            String valueString = "";
            if (null != value) {
                valueString = String.valueOf(value);
            }
            temp.append(valueString);
        });
        temp.append("&").append(ACCESS_SECRET).append("=").append(accessSecret);
        String str = DigestUtils.md5Hex(temp.toString()).toUpperCase();
        return str;
    }

    /**
     * 按键升序排列
     */
    private static <K, V> Map<K, V> sortByKeyAsc(Map<K, V> originMap) {
        if (originMap == null) {
            return null;
        }
        return originMap.entrySet()
                .stream()
                .sorted(
                        (Map.Entry o1, Map.Entry o2) -> {
                            if (o1.getKey() instanceof Comparable) {
                                return ((Comparable) o1.getKey()).compareTo(o2.getKey());
                            }
                            throw new UnsupportedOperationException("键的类型尚未实现Comparable接口");
                        })
                .collect(
                        Collectors.toMap(Map.Entry::getKey, Map.Entry::getValue, (e1, e2) -> e2,
                                LinkedHashMap::new)
                );
    }
}
